#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import config as c
from gitlab_map import site_map
import os
import re
from ftplib import FTP

root_path = c.local_www_path
# tpl_file_path = '/common/models/WorldpayLog.php'
tpl_file_path = '/common/oper/Cart.class.php'

pattern1 = "return\ \$realItemCount\ \=\=\ 0\;\s*\}"
new_str1 = '''return $realItemCount == 0;
    }

    /**
     * 获取需要展示多少盒子
     */
    public function getBoxCountAsync()
    {
        $db = self::getDb();
        $list = $this->getList();
        $newList = [];
        if ($list) {
            foreach ($list as $k2 => $v2) {
                // 父子sku依据的判断标识 0就是父sku， 1就是子sku
                $skuFlag = 0;
                $finalSku = '';
                $attrs = !empty($v2['c_attr_config']) ? json_decode($v2['c_attr_config'], true) : '';
                if ($attrs) {
                    foreach ($attrs as $key2 => $val2) {
                        if (!empty($val2[0]['sku'])) {
                            // 以子sku替换这个商品的父sku
                            $finalSku = $val2[0]['sku'];
                            $skuFlag ++;
                        }
                    }
                }
                if (!$skuFlag) {
                    $finalSku = $v2['g']['g_sku'];
                    $sql = "SELECT need_gift_box FROM t_goods WHERE g_sku = '{$finalSku}'";
                    $need = $db->getRow($sql);
                    if ($need && $need['need_gift_box'] == 0) {
                        $newList[$k2]['finalSku'] = $finalSku;
                        $newList[$k2]['gift_box_sku'] = '';
                        $newList[$k2]['num'] = $v2['g_number'];
                        continue;
                    }
                } else {
                    $sql = "SELECT c.* FROM t_goods AS a LEFT JOIN t_goods_cs_attr AS b ON a.g_id = b.g_id
                        LEFT JOIN t_goods_cs_attr_value AS c ON b.ca_id = c.ca_id 
                        WHERE ca_deleted = 0 AND cv_deleted = 0 AND c.sku = '{$finalSku}' GROUP BY c.sku";
                    $info = $db->getRow($sql);
                    if ($info && $info['need_gift_box'] == 0) {
                        $newList[$k2]['finalSku'] = $finalSku;
                        $newList[$k2]['gift_box_sku'] = '';
                        $newList[$k2]['num'] = $v2['g_number'];
                        continue;
                    }
                }
                // 看下有没有配置特殊礼盒
                $sql = "SELECT * FROM gift_box_set WHERE g_sku = '{$finalSku}'";
                $specialRet = $db->getRow($sql);
                // 如果有特殊礼盒配置就是特殊礼盒sku
                if ($specialRet) {
                    $newList[$k2]['finalSku'] = $finalSku;
                    $newList[$k2]['gift_box_sku'] = $specialRet['gbs_sku'];
                    $newList[$k2]['num'] = $v2['g_number'];
                } else {
	            // 否则就是通用礼盒
                    $sql = "SELECT * FROM gift_box_set WHERE gbs_special_set = 0";
                    $commonRet = $db->getRow($sql);
                    if ($commonRet) {
                        $newList[$k2]['finalSku'] = $finalSku;
                        $newList[$k2]['gift_box_sku'] = $commonRet['gbs_sku'];
                        $newList[$k2]['num'] = $v2['g_number'];
                    }
                }
            }
        }
        $giftBoxArr = [];
        // 这里进行礼盒的数量整合
        if ($newList) {
            $where = '';
            $giftBoxSku = array_unique(array_column($newList, 'gift_box_sku'));
            if ($giftBoxSku) {
                foreach ($giftBoxSku as $k => $v) {
                    if (empty($v)) continue;
                    $where .= "'" . trim($v) . "',";
                }
                $where = rtrim($where, ',');
            }
            // 这里已经整理出匹配到的礼盒，并查出信息
            $sql = "SELECT g_sku, gbs_sku, gbs_img, gbs_title, 0 as `number` FROM gift_box_set WHERE gbs_sku IN ({$where})";
            $giftBoxSetRet = $db->getAll($sql);
            $giftBoxSet = array_column($giftBoxSetRet, null,'gbs_sku');
            // 开始计数
            foreach ($newList as $k => $v) {
                $giftBoxSku = $v['gift_box_sku'];
                if (empty($giftBoxSku)) continue;
                if (isset($giftBoxSet[$giftBoxSku])) $giftBoxSet[$giftBoxSku]['number'] += $v['num'];
            }
            $giftBoxArr = $giftBoxSet;
        }

        return $giftBoxArr;
    }'''

def alter(file, new_str, pattern):
    try:
        with open(file, "r", encoding="utf-8") as f1, open("%s.bak" % file, "w", encoding="utf-8") as f2:
            content = f1.read()
            match_ret = re.search(pattern, content)
            flag = False

            if match_ret is None:
                print(file + ' ***** 异常: None,未匹配到 *****')
            else:
                text = re.sub(pattern, new_str, content)
                f2.write(text)
                flag = True

        if flag == True:
            os.remove(file)
            os.rename("%s.bak" % file, file)
            print(file + ' >>> 已完成')
    except Exception as e:
        print(file + ' ***** 异常 ***** >>> ' + str(e))

if __name__ == "__main__":
    for i in c.dirname_list:
        i = i.lower()
        dirname = site_map[i][35:][:-4].lower()
        project_path = root_path + dirname
        tpl = project_path + tpl_file_path
        alter(tpl, new_str1, pattern1)